import time

from sam import import_csv_path
from sam.util.fileUtil2 import read_file, write_file_quick
from sam.util.httpUtil import get_web_driver


class BaiduIndex(object):
    def __init__(self):
        super().__init__()
        self.browser = get_web_driver(headless=False, images_less=False)

    def login(self):
        self.browser.get("https://index.baidu.com/v2/index.html#/?login=1")
        time.sleep(1)
        userName = self.browser.find_element_by_css_selector(
            '#TANGRAM__PSP_4__userName')
        userName.send_keys("内乡店小二")
        password = self.browser.find_element_by_css_selector(
            '#TANGRAM__PSP_4__password')
        password.send_keys("mp@15037372431")
        submit = self.browser.find_element_by_css_selector(
            '#TANGRAM__PSP_4__submit')
        time.sleep(1)
        self.browser.execute_script("arguments[0].click();", submit)
        time.sleep(10)

    def search(self, keywords):
        self.browser.get(f"https://index.baidu.com/v2/main/index.html#/trend/{keywords}?words={keywords}")
        time.sleep(2)
        btnbtxt_list = self.browser.find_elements_by_css_selector(".btnbtxt")
        if btnbtxt_list and btnbtxt_list[0].text == '立即购买':
            return "未收录"
        dropdown_list = self.browser.find_elements_by_css_selector('.index-dropdown-list')
        self.browser.execute_script("arguments[0].click();", dropdown_list[0])
        item_list = self.browser.find_elements_by_css_selector('.list-item')
        self.browser.execute_script("arguments[0].click();", item_list[5])
        time.sleep(1)
        value_list = self.browser.find_elements_by_css_selector('.veui-table-cell')
        value_str = value_list[8].text
        replace = value_str.replace(",", "")
        return replace

    def main(self):
        line_list = read_file(import_csv_path)
        self.login()
        new_line_list = []
        for line in line_list:
            keywords = line[0].strip()
            if keywords:
                search_result = self.search(keywords)
                print(f"{keywords},{search_result}")
                new_line_list.append([keywords, search_result])
        else:
            export_file_name = "母婴-母婴"
            write_file_quick(data_list=new_line_list, export_file_name=export_file_name)
            if self.browser:
                self.browser.quit()
                print("无图浏览器退出")

    def __del__(self):
        if self.browser:
            self.browser.quit()
            print("无图浏览器退出")


if __name__ == "__main__":
    baiDuIndex = BaiduIndex()
    baiDuIndex.main()
